/**
 * 综合来看 fastjson 还是最优选择
 */
package com.zooltech.samples.jsonlibtest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

/**
 * @author yinxb
 * 
 */
public class JsonLibTest {
	/**
	 * 
	 */
	public JsonLibTest() {
		buildJsonString();
	}

	private void buildJsonString() {
		Group group = new Group();

		for (int i = 0; i < 200000; i++) {
			User user = new User();
			long n = Math.round(Math.random()*800000);
			user.setCreator("niles" + n);
			user.setId(1L);
			user.setImageUrl("img/class.png" + n);
			user.setInfo("Test user in group" + n);
			user.setName("test" + n);
			user.setVendor("class" + n);
			group.addUser(user);
		}
		try {
			System.err.println("start compare...");
			Gson gson = new Gson();


			long t0 = 0;
			long t1 = System.currentTimeMillis();
			String str = null;

			t0 = t1;
			ObjectMapper mapper = new ObjectMapper();
			str = mapper.writeValueAsString(group);
			t1 = System.currentTimeMillis();
			System.err.println("jackson serialize object:" + (t1 - t0));

			t0 = t1;
			str = JSON.toJSONString(group);
			//----去掉排序----
//	        SerializeWriter out = new SerializeWriter();
//	        try {
//	            JSONSerializer serializer = new JSONSerializer(out);
//	            serializer.config(SerializerFeature.SortField, false);
//	            serializer.write(group);
//	            str = out.toString();
//	        } finally {
//	            out.close();
//	        }
			//----去掉排序----
			t1 = System.currentTimeMillis();
			System.err.println("fastjson serialize object:" + (t1 - t0));
			System.out.println(str.substring(0, 2000));

			t0 = t1;
			str = gson.toJson(group);
			t1 = System.currentTimeMillis();
			System.err.println("Gson serialize object:" + (t1 - t0));

			System.err.println("--------------");

			t0 = t1;
			mapper = new ObjectMapper();
			Group group2 = mapper.readValue(str, Group.class);
			t1 = System.currentTimeMillis();
			System.err.println("jackson parse object:" + (t1 - t0));

			t0 = t1;
			Group group0 = JSON.parseObject(str, Group.class);
			t1 = System.currentTimeMillis();
			System.err.println("fastjson parse object:" + (t1 - t0));

			t0 = t1;
			Group group1 = gson.fromJson(str, Group.class);
			t1 = System.currentTimeMillis();
			System.err.println("Gson parse object:" + (t1 - t0));

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new JsonLibTest();
	}
}
